package com.atguigu.lease.common.utils;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;

public class JwtUtil {

  private static final Long expire=1000 * 60 * 60l;
 private static  SecretKey secretKey = Keys.hmacShaKeyFor("b8ad08a3a547e35829b821b75370301dd8c4b06bdd7771f9b541a75914068718".getBytes());//签名

  public static  String createToken(String userName,Long userId){

      String token = Jwts.builder()
              .setSubject("login-token") //token中的主题
              .setExpiration(new Date(System.currentTimeMillis() + expire))
              .claim("userId", userId)
              .claim("userName", userName)
              .signWith(secretKey)
              .compressWith(CompressionCodecs.GZIP)
              .compact();  //创建token
      return token;
  }
    public static Claims parseToken(String token){
        Jws<Claims> claimsJws = null;
        try {
            claimsJws = Jwts.parserBuilder().setSigningKey(secretKey).build().parseClaimsJws(token);
        } catch (ExpiredJwtException e) {
            throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);
        }catch (JwtException e){
            throw new LeaseException(ResultCodeEnum.TOKEN_INVALID);
        }
        return claimsJws.getBody();
    }

    public static void main(String[] args) {

        String token = createToken("admin", 1L);
        System.out.println(token);
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        Claims claims = parseToken(token);
        System.out.println(claims);

    }
}
